<template>
  <div class="app-container">
    <!-- 工艺卡 -->

    <el-row :gutter="24">
      <el-col :lg="24" :xs="24">
        <div class="search-bar">
          <!-- 搜索 -->
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="工艺编号" prop="code">
              <el-input
                v-noSpace
                v-model="queryParams.code"
                class="!w-[192px]"
                placeholder="请输入工艺编号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>

            <el-form-item label="工序名称" prop="processCode">
              <el-select
                v-model="queryParams.processCode"
                placeholder="请选择工序名称"
                class="!w-[192px]"
                clearable
                filterable
                @change="handleQuery"
                @visible-change="getName"
              >
                <el-option
                  v-for="item in optionsName"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-select
                v-model="queryParams.status"
                class="!w-[192px]"
                placeholder="请选择状态"
                clearable
                @change="handleQuery"
              >
                <el-option label="启用" value="0" />
                <el-option label="停用" value="1" />
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
              <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
              <el-button
                type="warning"
                icon="plus"
                @click="handleEdit({}, 'add')"
                v-hasPerm="'sys:processCard:edit'"
              >
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never">
          <el-table v-loading="loading" :data="pageData" show-overflow-tooltip>
            <el-table-column prop="code" label="工艺编号" align="center" />
            <el-table-column prop="processName" label="工序名称" align="center" />
            <el-table-column prop="processCode" label="工序编号" align="center" />
            <el-table-column prop="productSpec" label="成品规格" align="center" />
            <el-table-column prop="stepName" label="作业顺序名称" align="center" />
            <el-table-column prop="qualityName" label="品质要求" align="center" />
            <el-table-column prop="toolName" label="工具名称" align="center" />
            <el-table-column prop="toolName" label="是否启用" align="center">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.status"
                  :active-value="0"
                  :inactive-value="1"
                  @change="handleStatusChange(scope.row.status, scope.row)"
                />
              </template>
            </el-table-column>

            <el-table-column label="操作" fixed="right" width="250" align="center">
              <template #default="scope">
                <el-button
                  type="primary"
                  size="small"
                  link
                  @click="handleEdit(scope.row, 'edit')"
                  v-hasPerm="'sys:processCard:edit'"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  size="small"
                  link
                  @click="handleDel(scope.row)"
                  v-hasPerm="'sys:processCard:del'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="700px"
      class="df"
      @close="handleCloseDialog"
    >
      <el-form
        ref="dialogFormRef"
        :model="dialogParams"
        :inline="true"
        label-width="130px"
        :rules="rules"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="工序名称" prop="processName">
              <el-select
                v-model="dialogParams.processName"
                placeholder="请选择工序名称"
                clearable
                filterable
                style="width: 192px"
                @change="changeName"
                @visible-change="getName"
              >
                <el-option
                  v-for="item in optionsName"
                  :key="item.value"
                  :label="item.label"
                  :value="item"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="工序编号" prop="processCode">
              <el-input
                v-noSpace
                v-model="dialogParams.processCode"
                placeholder="请输入工序名称"
                clearable
                maxlength="100"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品规格" prop="productSpec">
              <el-input
                v-noSpace
                v-model="dialogParams.productSpec"
                placeholder="请输入成品规格"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" />

          <el-col :span="12">
            <el-form-item label="作业顺序" prop="stepName">
              <el-input
                v-noSpace
                v-model="dialogParams.stepName"
                placeholder="请输入作业顺序"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上传作业顺序图片" prop="stepImg">
              <FileUpload
                v-model="dialogParams.stepImg"
                :data="{ bizType: 'contract' }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="品质要求" prop="qualityName">
              <el-input
                v-noSpace
                v-model="dialogParams.qualityName"
                placeholder="请输入品质要求"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上传品质要求图片" prop="qualityImg">
              <!-- <MultiImageUpload v-model="dialogParams.qualityImg" :data="{ bizType: 'contract' }" /> -->
              <!-- <FileUpload
                v-model:model-value="dialogParams.qualityImg"
                uploadBtnText="点击上传"
                :showTip="true"
                :data="{ bizType: 'contract' }"
                :maxSize="5 * 1024 * 1024"
                @update:modelValue="handleUpdateFileInfoJson(dialogParams.qualityImg, 'qualityImg')"
                :showFileList="false"
              ></FileUpload> -->
              <FileUpload
                v-model="dialogParams.qualityImg"
                :data="{ bizType: 'contract' }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="工具用品" prop="toolName">
              <el-input
                v-noSpace
                v-model="dialogParams.toolName"
                placeholder="请输入工具用品"
                clearable
                maxlength="100"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="上传工具用品图片" prop="toolImage">
              <!-- <MultiImageUpload v-model="dialogParams.toolImage" :data="{ bizType: 'contract' }" /> -->
              <FileUpload
                v-model="dialogParams.toolImage"
                :data="{ bizType: 'contract' }"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer df">
          <el-button v-debounce="submitDialog" type="primary">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import processCardAPI, { processPageQuery, processPageVO } from "@/api/processCard/processCard";
import configApi, { ConfigType } from "@/api/config/config";
import { FormItemRule } from "element-plus/es";

defineOptions({
  name: "User",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);

const queryParams = reactive<processPageQuery>({
  pageNum: 1,
  pageSize: 10,
});

const optionsName = ref<{ value: string; label: string }[]>([]); // 显式指定类型

const pageData = ref<processPageVO[]>();
const total = ref(0);
const listTotal = ref(0);
const loading = ref(false);

// 新增/修改弹窗
const dialog = reactive({
  visible: false,
  title: "",
  type: "",
});
const dialogFormRef = ref(ElForm);

const dialogParams = reactive({
  processName: "",
  processCode: "",
  productSpec: "",
  stepName: "",
  stepImg: [],
  qualityName: "",
  qualityImg: [],
  toolName: "",
  toolImage: [],
});

const options = [
  {
    value: "Option1",
    label: "Option1",
  },
  {
    value: "Option2",
    label: "Option2",
  },
  {
    value: "Option3",
    label: "Option3",
  },
  {
    value: "Option4",
    label: "Option4",
  },
  {
    value: "Option5",
    label: "Option5",
  },
];

//是否启用
const handleStatusChange = (status: any, row: any) => {
  console.log(status);

  processCardAPI.submitDialog({ id: row.id, status }).then((res) => {
    ElMessage.success("操作成功");
    handleQuery();
  });
};

const rules = reactive<Record<string, FormItemRule[]>>({
  processName: [{ required: true, message: "工序名称是必填项", trigger: "blur" }],
  processCode: [{ required: true, message: "工序编号是必填项", trigger: "blur" }],
  productSpec: [{ required: true, message: "成品规格是必填项", trigger: "blur" }],
  stepName: [{ required: true, message: "作业顺序是必填项", trigger: "blur" }],
  qualityName: [{ required: true, message: "品质要求是必填项", trigger: "blur" }],
  toolName: [{ required: true, message: "工具用品是必填项", trigger: "blur" }],
});
//产品列表 potato carrot beef
const productList = ref<
  {
    codeName: string;
    codeValue: string;
  }[]
>([]);
const getProductName = () => {
  configApi.getConfigListByType(ConfigType.PROD_CODE).then((res) => {
    productList.value = res;
  });
};

// 查询
function handleQuery() {
  // loading.value = true;
  console.log("queryParams", queryParams);
  processCardAPI
    .getPage(queryParams)
    .then((data) => {
      pageData.value = [...(data?.list as any)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  // queryParams.deptId = undefined;
  // queryParams.createTime = undefined;
  handleQuery();
}

onMounted(() => {
  handleQuery();
  // handleTotal();
});

function handleEdit(row: any, type: any) {
  dialog.type = type;
  if (type == "edit") {
    dialog.title = "编辑";
    // 将 row.qualityImg 从字符串转换为数组
    if (typeof row.qualityImg === "string") {
      row.qualityImg = row.qualityImg.split(",").map((url: any) => {
        const name = url.split("/").pop(); // 提取文件名
        return { name, url };
      });
    }
    if (typeof row.stepImg === "string") {
      row.stepImg = row.stepImg.split(",").map((url: any) => {
        const name = url.split("/").pop(); // 提取文件名
        return { name, url };
      });
    }
    if (typeof row.toolImage === "string") {
      row.toolImage = row.toolImage.split(",").map((url: any) => {
        const name = url.split("/").pop(); // 提取文件名
        return { name, url };
      });
    }
    Object.assign(dialogParams, { ...row });
    // row.qualityImg = "contract/2025/01/24/货车 (4) (1).png,contract/2025/01/24/货车 (3) (2).png"
    // dialogParams.qualityImg = [ { "name": "货车 (4) (1).png", "url": "contract/2025/01/24/货车 (4) (1).png" }, { "name": "货车 (3) (2).png", "url": "contract/2025/01/24/货车 (3) (2).png" }]
  } else {
    dialog.title = "新增";
    clearDialogFormData();
  }
  dialog.visible = true;
}

function handleDel(row: any) {
  ElMessageBox.confirm("确定要删除该数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      processCardAPI
        .delDialog({ id: row.id })
        .then((data) => {
          ElMessage.success("操作成功");
          handleQuery();
        })
        .catch((err) => {
          // ElMessage.error(`${err}`);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(() => {
      // 取消删除
    });
}

function handleCloseDialog() {
  dialog.visible = false;
}

//重置弹窗
function clearDialogFormData() {
  let data = {
    processName: "",
    processCode: "",
    productSpec: "",
    stepName: "",
    stepImg: [],
    qualityName: "",
    qualityImg: [],
    toolName: "",
    toolImage: [],
  };
  Object.assign(dialogParams, { ...data });
}

// 提交弹窗
function submitDialog() {
  dialogFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return;
    }
    console.log("dialogParams", dialogParams);
    let paramsData = <any>{};
    if (dialog.title == "新增") {
      paramsData = {
        processName: dialogParams.processName,
        processCode: dialogParams.processCode,
        productSpec: dialogParams.productSpec,
        stepName: dialogParams.stepName,
        qualityName: dialogParams.qualityName,
        toolName: dialogParams.toolName,
        stepImg: dialogParams.stepImg,
        qualityImg: dialogParams.qualityImg,
        toolImage: dialogParams.toolImage,
      };
    } else {
      paramsData = { ...dialogParams };
    }

    // 转换 stepImg 数组为逗号分隔的字符串
    paramsData.stepImg = paramsData.stepImg.map((item: any) => item.url).join(",");
    paramsData.qualityImg = paramsData.qualityImg.map((item: any) => item.url).join(",");
    paramsData.toolImage = paramsData.toolImage.map((item: any) => item.url).join(",");
    processCardAPI
      .submitDialog(paramsData)
      .then((data) => {
        ElMessage.success("操作成功");
        dialog.visible = false;
        handleQuery();
        clearDialogFormData();
      })
      .catch((err) => {
        // ElMessage.error(`${err}`);
      })
      .finally(() => {
        loading.value = false;
      });
  });
}

const getName = () => {
  processCardAPI
    .getName({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      optionsName.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.name,
        capacity: item.capacity,
      }));
    })
    .finally(() => {});
};

function handleUpdateFileInfoJson(fileInfoJson: any, type: string) {
  console.log(fileInfoJson, "2");
  console.log(type, "2");
  // let submitFileInfo = JSON.parse(infoFormData.fileInfoJson || "[]");
  // submitFileInfo = [fileInfoJson[fileInfoJson.length - 1], ...submitFileInfo];
  // infoFormData.fileInfoJson = JSON.stringify(submitFileInfo);
}
function changeName(val: any) {
  dialogParams.processCode = val.value;
  dialogParams.processName = val.label;
}
</script>

<style lang="scss" scoped>
:deep(.el-upload-list__item-name) {
  width: 200px !important;
}
</style>
